<template>
	<div>
		<!-- <div>{{ node.name }}</div> -->
		<div v-if="flowSource">
			<a-button v-if="flowSource.status === 0" type="primary" danger @click="showFlowModel(flowSource)">待审核</a-button>
			<a-button v-else-if="flowSource.status === 1" type="primary" @click="showFlowModel(flowSource)">审核中</a-button>
			<a-button v-else-if="flowSource.status === -1" type="primary" danger @click="showFlowModel(flowSource)">已退回</a-button>
			<a-button v-else-if="flowSource.status === 2" type="primary" danger disabled @click="showFlowModel(flowSource)">已完成</a-button>
		</div>
		<div v-else>
			<a-button type="primary" @click="createFlow">生成</a-button>
		</div>
		<a-modal v-model:visible="visible" :width="700" :title="`${formState.id ? '修改' : '添加'}审批流`">
			<a-form ref="formRef" :model="formState" v-bind="{labelCol: { style: { width: '100px' } }}">
				<a-form-item label="名称" name="name" :rules="{required:true, message:'请输入名称'}">
					<a-input v-model:value="formState.name" :disabled="inputDisable('name',formType)" />
				</a-form-item>
				<a-form-item label="审批类型" name="type_id">
					<a-radio-group v-model:value="formState.type_id" button-style="solid" @change="changeTypeId">
						<a-radio-button v-for="item in flowTypeSource" :key="item.id" :value="item.id" :style="formState.type_id===item.id?'color:red':''" :disabled="inputDisable('type_id',formType)">{{ item.name }}</a-radio-button>
					</a-radio-group>
					<!-- 					<a-select v-model:value="formState.type_id" style="width: 120px">
						<a-select-option :value="item.id" v-for="item in flowTypeSource" :key="item.id">{{item.name}}</a-select-option>
					</a-select>-->
				</a-form-item>
				<a-form-item label="模块id" name="module_id" :rules="{required:true, message:'请输入模块id'}">
					<a-input v-model:value="formState.module_id" :disabled="inputDisable('module_id',formType)" />
				</a-form-item>
				<a-form-item label="项目id" name="item_id" :rules="{required:true, message:'请输入项目id'}">
					<a-input v-model:value="formState.item_id" :disabled="inputDisable('item_id',formType)" />
				</a-form-item>
				<a-form-item label="审批角色" name="role_ids" :rules="{required:true, message:'请选择审批角色'}">
					<a-checkbox-group v-model:value="role_ids" style="width: 100%" @change="changeDepts">
						<a-row>
							<a-col v-for="item in roles" :key="item.id" :span="8">
								<a-checkbox :value="item.id" :disabled="inputDisable('role_ids',formType)">{{ item.name }}</a-checkbox>
							</a-col>
						</a-row>
					</a-checkbox-group>
				</a-form-item>
				<a-form-item label="审批状态" name="status" :rules="{required:true, message:'选择审批状态'}">
					<a-radio-group v-model:value="formState.status" button-style="solid">
						<a-radio v-for="item in flowStatus" :key="item.status" :value="item.status" :disabled="inputDisable('status',formType)">{{ item.name }}</a-radio>
						<!-- <a-radio value="-1">拒绝</a-radio> -->
						<!-- <a-radio-button value="d">提交给其他角色</a-radio-button> -->
					</a-radio-group>
				</a-form-item>
				<a-form-item label="备注" name="remark">
					<a-input v-model:value="formState.remark" :disabled="inputDisable('remark',formType)" />
				</a-form-item>
			</a-form>
			<template #footer>
				<a-button v-if="authAct('refresh')" @click="run">刷新</a-button>
				<a-button v-if="authAct('updateStatusOk')" type="primary" :disabled="formState.status !== 1" @click="updateStatusOk">完成</a-button>
				<a-button key="back" @click="handleCancel">取消</a-button>
				<a-button v-if="authAct('update')" type="primary" :disabled="formState.status === 0" @click="updateFlowApi">更新提交</a-button>
				<a-button v-if="formType === 'create' && authAct('create')" type="primary" @click="createFlowApi">立即创建</a-button>
			</template>
		</a-modal>
	</div>
</template>
<script setup lang="ts">
/**
 * 项目审核状态操作
 */
import { ref, watch, onMounted, getCurrentInstance, reactive } from "vue";
import { post, treeToList } from "../utils";
import { useRequest } from "vue-request";
import router from "../router";
import dayjs from "dayjs";
const { proxy } = getCurrentInstance();
const roles = ref();
const flowStatus = ref();
const flowSource = ref();
const flowNodes = ref();
const flowTypeSource = ref();
const role_ids = ref();
flowStatus.value = [
	{ status: -1, name: "退回" },
	{ status: 0, name: "待审核" },
	{ status: 1, name: "通过" },
	{ status: 2, name: "完成" }
];
const formType = ref();
// 表单输入框 禁用状态
const inputDisable = (node, type) => {
	var disable = {
		name: {
			create: false,
			update: true
		},
		status: {
			create: true,
			update: true
		},
		type_id: {
			create: true,
			update: true
		},
		role_ids: {
			create: false,
			update: false
		},
		module_id: {
			create: true,
			update: true
		},
		item_id: {
			create: true,
			update: true
		}
	};
	if (node in disable && type in disable[node] && disable[node][type]) {
		return true;
	}
	return false;
};
// 用户操作权限
// role_ids
const authAct = act => {
	if (act === "update") {
		return true;
	} else if (act === "create") {
		return true;
	}
	return true;
};
// 必填flowId 或者 (moduleId,itemId)
const props = defineProps({
	// 审批项id
	flowId: {
		type: Number,
		required: false,
		default: 0
	},
	// 模块标识
	moduleId: {
		type: String,
		required: false,
		default: ""
	},
	// 模块下内容id
	itemId: {
		type: Number,
		required: false,
		default: 0
	}
});

//定义emit
const emit = defineEmits(["update:flowId", "update:moduleId", "update:itemId", "change"]);

const getFlowTypeList = async () => {
	return post("flow/getFlowTypeList", {}).then(({ data }) => {
		emit("change", { act: "flowTypeList", data });
		flowTypeSource.value = data;
		// flowTypeSource.value = data.map((d) => {
		// 	return d;
		// });
	});
};
const params = ref();
const changeDepts = e => {
	if (role_ids.value) formState.value.role_ids = role_ids.value.join(",");
};

const initflowTypeSource = (typeid, moduleId) => {
	const data = flowTypeSource.value.map(e => {
		if (e.id === typeid || moduleId === e.module_id) {
			// console.log(e);
			if (e.roles) {
				var depts = e.roles;
				roles.value = depts;
			}
			params.value.type_id = e.id;
			params.value.module_id = e.module_id;
			if (!formState.value.name) {
				formState.value.name = e.name;
			}
			formState.value.type_id = e.id;
			formState.value.module_id = e.module_id;
			return e;
		}
	});
};
onMounted(async () => {
	// console.log(props);
	await getFlowTypeList();
	if (props.flowId !== 0) {
		params.value = { id: props.flowId };
		run();
	} else if (props.moduleId !== "" && props.itemId !== 0) {
		params.value = { module_id: props.moduleId, item_id: props.itemId };
		initflowTypeSource(null, props.moduleId);

		run();
	}
});

const visible = ref(false);
const formRef = ref();
const formState = ref({});
const checkBoxChange = item => {
	// role_ids.value = [item.id];
	// const typeid = item.target.value;
	// initflowTypeSource(typeid);
};
const changeTypeId = item => {
	const typeid = item.target.value;
	initflowTypeSource(typeid);
};

const run = () => {
	post("flow/info", params.value).then(data => {
		// console.log(data, params.value);
		if (!data.id) {
			return;
		}
		if (props.flowId !== data.id) {
			emit("update:flowId", data.id);
		}
		if (props.itemId !== data.item_id) {
			emit("update:itemId", data.item_id);
		}
		if (props.moduleId !== data.module_id) {
			emit("update:moduleId", data.module_id);
		}
		var idx = 0;
		flowNodes.value = data.flowNodes.filter(e => {
			idx++;
			e.idx = idx;
			e.update_time = dayjs(e.update_time).format("YYYY-MM-DD HH:mm:ss");
			return e;
		});
		// console.log(data.flowType)
		if (data.flowType) {
			var depts = data.flowType.roles;
			// var depts = roles.value;
			depts = depts.map(item => {
				item.flowNodes = [];
				flowNodes.value.map(flownode => {
					if (flownode.role_id === item.id) {
						item.flowNodes.push(flownode);
						if (item.status !== 0) {
							item.status = flownode.status;
						}
					}
				});
				return item;
			});
			// console.log(depts)
			roles.value = depts;
			data.flowType.roles = depts;
		} else {
			data.flowType = {};
			roles.value = {};
			data.flowType.roles = {};
		}
		flowSource.value = data;
		emit("change", { act: "flowInfoData", data: data });
		// console.log(flowSource.value)
	});
};
// watch(props.flowId, (value) => {
// 	console.log(value);
// 	// if (props.flowId !== 0) {
// 	// 	run();
// 	// }
// });
// watch(flowNodes, (value) => {
// 	for (const i in roles.value) {
// 		roles.value[i].flowNodes = value.filter((d) => {
// 			if (d.role_id === roles.value[i].id) {
// 				return d;
// 			}
// 		});
// 		if (roles.value[i].flowNodes.length > 0) {
// 			roles.value[i].status =
// 				roles.value[i].flowNodes[
// 					roles.value[i].flowNodes.length - 1
// 				].status;
// 		}
// 	}
// });

const showFlowModel = async record => {
	formRef.value?.clearValidate();
	visible.value = true;

	const data = { ...record };
	// var depts = record.flowNodes;
	if (data.role_ids) {
		role_ids.value = data.role_ids.split(",").map(d => parseInt(d));
	}
	formState.value = data;
	formType.value = formState.value.id ? "update" : "create";
	// console.log(formState.value);
	initflowTypeSource(data.type_id, data.module_id);
};
const createFlow = () => {
	params.value.status = 0;
	showFlowModel(params.value);
};
const formValidate = () => {
	return new Promise(resolve => {
		params.value = { ...formState.value };
		if (role_ids.value) {
			params.value.role_ids = role_ids.value.join(",");
		}
		formRef.value
			.validate()
			.then(() => {
				proxy.$message.destroy();
				resolve(params.value);
			})
			.catch(err => {
				// proxy.$message.error(err);
			});
	});
};
// 用户权限创建接口
const createFlowApi = () => {
	if (!authAct("create", "flow:create")) {
		proxy.$message.error("创建权限不够");
		return;
	}
	formValidate().then(param => {
		post("flow/userCreate", { ...param })
			.then(() => {
				proxy.$message.success("行业信息提交成功", 1);
				visible.value = false;

				// expandedRowKeys.value.push(params.parent_id);
				emit("change", { act: "createFlow", status: 1 });
				run();
			})
			.catch(err => {
				proxy.$message.error(err);
			});
	});
};
const updateStatusOk = () => {
	var count = flowSource.value.flowNodes.findIndex(e => {
		return e.status === 0;
	});
	if (count > -1) {
		proxy.$message.error("对不起，有节点处于待审核状态");
		return;
	}
	if (flowSource.value.status !== 1) {
		proxy.$message.error("有未完成状态，或已完成");
		return;
	}

	post("flow/updateStatusOk", { id: flowSource.value.id })
		.then(() => {
			emit("change", { act: "updateStatus", flowSource });
			proxy.$message.success("更新成功", 1);
			visible.value = false;
		})
		.catch(err => {
			proxy.$message.error(err);
		});
};
// 用户权限更新接口
const updateFlowApi = () => {
	if (!authAct("update", "flow:create")) {
		proxy.$message.error("更新权限不够");
		return;
	}
	formValidate().then(param => {
		post("flow/userUpdate", { ...param, status: 0 })
			.then(() => {
				proxy.$message.success("行业信息提交成功", 1);
				visible.value = false;

				// expandedRowKeys.value.push(params.parent_id);
				emit("change", { act: "updateFlow", status: 1 });
				run();
			})
			.catch(err => {
				proxy.$message.error(err);
			});
	});
};

// 管理员权限 创建或更新
const saveFlow = () => {
	formValidate().then(e => {
		post("flow/save", { ...params.value })
			.then(() => {
				proxy.$message.success("行业信息提交成功", 1);
				visible.value = false;

				// expandedRowKeys.value.push(params.parent_id);
				emit("change", { act: "flowSave", status: 1 });
				run();
			})
			.catch(err => {
				proxy.$message.error(err);
			});
	});
};
watch(visible, value => {
	if (value) formRef.value?.clearValidate();
});
const handleCancel = () => {
	visible.value = false;
};
// run();
</script>